package com.szyt.basicframe.controller;

import com.google.code.kaptcha.Producer;
import com.szyt.basicframe.service.ICaptchaService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
@RequestMapping("/captcha")
@Api(tags = "验证码")
@Slf4j
public class CaptchaController {

    @Autowired
    private Producer kaptchaProducer;

    @Autowired
    private ICaptchaService captchaService;

    @GetMapping("/image")
    @ApiOperation("获取验证码")
    public void getImageCaptcha(HttpServletResponse response, HttpServletRequest request) throws IOException {
        // 清除浏览器缓存
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        // 创建验证码文本
        String capText = kaptchaProducer.createText();
        log.info("生成验证码：" + capText);

        // 获取会话ID
        String sessionId = request.getSession().getId();

        // 存储验证码
        captchaService.storeCaptcha(sessionId, capText);

        // 创建验证码图片
        BufferedImage image = kaptchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();

        // 输出图片
        ImageIO.write(image, "jpg", out);
        out.flush();
        out.close();
    }
}
